/**
 * Copyright (C) 2017-2018 pinganfang, Inc. All Rights Reserved.
 */
package com.pingan.haofang.searchcloud.solr.api;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.wltea.analyzer.lucene.IKAnalyzer;


/**
 * @author huhailiang937
 * @date 2017年4月24日下午8:53:19
 * @since 1.0.0
 */
public class IKSegmentSupport {

    private static final Logger logger = LoggerFactory.getLogger(IKSegmentSupport.class);

    /**
     * 分词
     * @param keyword：分词值
     * @param isSmart：是否智能分词
     * @return
     *
     */
    public static String segment(String keyword,boolean isSmart) {
        return StringUtils.join(segment("my_ik",keyword,isSmart)," ");
    }
    
    /**
     * 分词
     * @param keyword：分词值
     * @param isSmart：是否智能分词
     * @return
     *
     */
    public static List<String>  segmentList(String keyword,boolean isSmart) {
        return segment("my_ik",keyword,isSmart);
    }
    
    
    /**
     * 分词
     * @param keyword：分词值
     * @param isSmart：是否智能分词
     * @return
     *
     */
    public static List<String> segment(String fileName,String keyword,boolean isSmart) {
        Assert.notNull(fileName,"fileName can not null");
        TokenStream ts = null;
        List<String> resList = new ArrayList<String>();
        try {
            if(isSmart){
                ts =  new IKAnalyzer(true).tokenStream(fileName, new StringReader(keyword));
            }else{
                ts =  new IKAnalyzer(false).tokenStream(fileName, new StringReader(keyword));
            }
            CharTermAttribute term = (CharTermAttribute) ts.addAttribute(CharTermAttribute.class);
            ts.reset();
            

            while (ts.incrementToken()) {
                resList.add(term.toString());
            }
            ts.end();

        } catch (IOException e) {
            logger.error("IKAnalyzer has error： " + e.getMessage(), e);
            if (ts != null)
                try {
                    ts.close();
                } catch (IOException e1) {
                    logger.error("IKAnalyzer has error： " + e.getMessage(), e);
                }
        } finally {
            if (ts != null)
                try {
                    ts.close();
                } catch (IOException e) {
                    logger.error("IKAnalyzer has error： " + e.getMessage(), e);
                }
        }
        return resList;
    }
}
